package br.com.eventest.dao;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;


public abstract class GenericDao<T, E extends Serializable> implements Serializable {
	
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@PersistenceContext(unitName = "EvenTest")
	protected EntityManager em;
	
	
	public T merge(T entidade){
		em.merge(entidade);
		return entidade;
	}
	
	@SuppressWarnings("unchecked")
	public void delete(T entidade, E chave){
		entidade = (T) em.getReference(entidade.getClass(), chave);
		em.remove(entidade);
	}
	
	public T find(Class<T> clazz,E chave){
		return em.find(clazz,chave);
	}
	
	@SuppressWarnings("unchecked")
	public List<T> findToList(String namedQuery, Object ... parameters){
		Query query = em.createNamedQuery(namedQuery);
		for (int i = 0 ; i < parameters.length ; i++){
			query.setParameter(i, parameters[i]);
		}
		return query.getResultList();
	}

	public void setEm(EntityManager em) {
		this.em = em;
	}

}
